package com.apkfuns.jsbridge;

import com.apkfuns.jsbridge.slice.MainAbilitySlice;
import com.apkfuns.jsbridge.view.base.BaseAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.security.SystemPermission;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

public class MainAbility extends BaseAbility {
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        requestCameraPermission();
        getWindow().setStatusBarColor(Color.BLACK.getValue());
    }

    private void requestCameraPermission() {
        List<String> permissions =
                new LinkedList<String>(
                        Arrays.asList(
                                SystemPermission.WRITE_USER_STORAGE,
                                SystemPermission.READ_USER_STORAGE,
                                SystemPermission.CAMERA,
                                SystemPermission.LOCATION));//
//        permissions.removeIf(
//                permission ->
//                        verifySelfPermission(permission) == PERMISSION_GRANTED || !canRequestPermission(permission));
//
        for (String permission : permissions){
            if (verifySelfPermission(permission) == PERMISSION_GRANTED || !canRequestPermission(permission)) {
                permissions.remove(permission);
            }
        }

        if (!permissions.isEmpty()) {
            requestPermissionsFromUser(permissions.toArray(new String[permissions.size()]), PERMISSION_REQUEST_CODE);
        }
    }


    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode != PERMISSION_REQUEST_CODE) {
            new ToastDialog(this).setText("权限被拒绝").show();
            terminateAbility();
            return;
        }
        for (int grantResult : grantResults) {
            if (grantResult != PERMISSION_GRANTED) {
                new ToastDialog(this).setText("权限被拒绝").show();
                terminateAbility();
                return;
            }
        }

    }
}
